import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
class ServerThread implements Runnable{
    private Socket socket;
    public ServerThread(Socket socket) {
        this.socket = socket;
    }
    @Override
    public void run() {
        // 1.处理客户端请求，上传路径
        String ipString = socket.getInetAddress().getHostAddress();
        // 通过file类操作文件
        File pFile = new File("G:\\data\\");
        if (!pFile.exists()){
            pFile.mkdir();  // 创建文件夹
        }
        // 把客户端的ip地址作为文件名
        File file = new File(pFile,ipString+".jpg");
        try {
            // 通过客户端在Inputstream中读入
            InputStream inputStream = socket.getInputStream();
            // 将读取的字节流写入文件
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buf))!=-1){
                fos.write(buf,0,len);
            }
            //服务器端向客户端做出响应，返回信息
            OutputStream out = socket.getOutputStream();
            out.write("上传成功".getBytes());
            // 关闭
            inputStream.close();
            fos.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class FilePut {
    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(3000);
            while (true){
                // 阻塞状态，准备接收客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("服务器端与客户端连接，开始接受信息");
                new Thread(new ServerThread(clientSocket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
